package com.ys.web.user.privacy;

import com.alibaba.fastjson.JSON;
import com.ys.utils.base.http.McodeHandler;
import com.ys.utils.base.j2se.Common;
import com.ys.utils.base.j2se.Convert;
import com.ys.utils.base.j2se.StringHandler;
import com.ys.utils.redis.Redis;
import com.ys.utils.redis.key.UserKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class PrivacyManager {
    @Autowired
    private PrivacyMapper privacyMapper;
    private static PrivacyMapper privacyDao;

    @PostConstruct
    void init() {
        privacyDao = this.privacyMapper;
    }

    //根据用户id批量初始化隐私设置
    public static void init(List<String> uids) {
        uids = uids.stream().peek(McodeHandler::from32Radix).collect(Collectors.toList());
        List<Privacy> privacyList = privacyDao.getPrivacyByIds(uids);
        privacyList.forEach(x -> {
            String key = UserKey.getPrivacyConfigKey(x.getUserId());
            Redis.str.set(key, JSON.toJSONString(x), 3600);
        });
    }

    //根据用户id批量初始化隐私设置
    public static List<Privacy> getPrivacyByIds(List<String> uids) {
        uids = uids.stream().map(x -> String.valueOf(McodeHandler.from32Radix(x))).collect(Collectors.toList());
        return privacyDao.getPrivacyByIds(uids);
    }

    //手机号屏蔽接口
    public static boolean hidePhone(long userId) {
        Privacy privacy  = getPrivacy(userId);
        if(StringHandler.isEmpty(privacy)){
            return false;
        }
        return privacy.getHidePhone();
    }

    //二维码屏蔽接口
    public static boolean hideQrcode(long userId) {
        Privacy privacy  = getPrivacy(userId);
        if(StringHandler.isEmpty(privacy)){
            return false;
        }
        return privacy.getHideQrcode();
    }

    //添加好友需要验证接口
    public static boolean friendVerify(Object userId) {
        return getPrivacy(StringHandler.getLong(userId)).getFriendVerify();
    }

    //群聊屏蔽接口-->用户不允许邀请进入群聊
    public static boolean hideGroup(Object userId) {
        return getPrivacy(StringHandler.getLong(userId)).getHideGroup();
    }

    //邀请进群验证接口
    public static boolean groupVerify(Object userId) {
        return getPrivacy(StringHandler.getLong(userId)).getGroupVerify();
    }

    private static Privacy getPrivacy(long userId) {
        String key = UserKey.getPrivacyConfigKey(userId);
        String data = Redis.str.getAndExpire(key, 3600);
        Privacy privacy;
        if (StringHandler.isEmpty(data)) {
            privacy = privacyDao.getPrivacyById(userId);
            Redis.str.set(key, JSON.toJSONString(privacy), 3600);
        } else {
            privacy = JSON.parseObject(data, Privacy.class);
        }
        return privacy;
    }
}
